package org.gpf.util;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

public class FileUploadTool {

	private HttpServletRequest request = null;
	private List<FileItem> items = null;
	private Map<String, List<String>> params = new HashMap<String, List<String>>();
	private Map<String, FileItem> files = new HashMap<String, FileItem>();
	
	@SuppressWarnings("unchecked")
	public FileUploadTool(HttpServletRequest request,long maxSize,String tmpDir) throws FileUploadException {
		this.request = request;
		DiskFileItemFactory factory = new DiskFileItemFactory();
		if (tmpDir != null) {
			factory.setRepository(new File(tmpDir));
		}
		ServletFileUpload upload = new ServletFileUpload(factory);
		if (maxSize > 0) {
			upload.setSizeMax(maxSize);
		}
		this.items = upload.parseRequest(request);
		this.init();
	}
	
	public void init(){
		Iterator<FileItem> iterator = this.items.iterator();
		IPTimeStamp ipts = new IPTimeStamp(request.getRemoteAddr());
		while (iterator.hasNext()) {
			FileItem fileItem = (FileItem) iterator.next();
			
			if (fileItem.isFormField()) { 				// 普通参数
				String name = fileItem.getFieldName();
				String value = fileItem.getString();
				List<String>temp = null;
				if (this.params.containsKey(name)) {
					temp = this.params.get(name);
				}else{
					temp = new ArrayList<String>();
				}
				temp.add(value);
				this.params.put(name, temp);
			}else {										// 文件
				String filename = ipts.getIPTimeRand() + "." + fileItem.getName().split("\\.")[1];
				this.files.put(filename, fileItem);
			}
		}
	}
	
	/**
	 * 根据名称取得参数名称取得内容
	 * @param name
	 * @return
	 */
	public String getParameter(String name){
		
		String ret = null;
		List<String> temp = this.params.get(name);
		if (temp!=null) {
			ret = temp.get(0);
		}
		return ret;
	}
	
	public String[]  getParameterValues(String name){
		
		String[] ret = null;
		List<String> temp = this.params.get(name);
		if (temp!=null) {
			ret = temp.toArray(new String[]{});
		}
		return ret;
	}
	
	public Map<String, FileItem> getUploadFiles(){
		
		return this.files;
	}
	
	public List<String> saveAll(String saveDir) throws IOException {
		
		List<String> names = new ArrayList<String>();
		if (this.files.size() > 0) {
			Set<String> keys = this.files.keySet();		// key是文件名称
			Iterator<String> iterator = keys.iterator();
			File saveFile = null;
			InputStream input = null;
			OutputStream out = null;
			
			while (iterator.hasNext()) {
				FileItem item = this.files.get(iterator.next());
				String filename = new IPTimeStamp(request.getRemoteAddr()).getIPTimeRand() + "." + item.getName().split("\\.")[1];
				saveFile = new File(saveDir + filename);
				names.add(filename);	// 名字不返回后期无法操作
				
				try {
					input = item.getInputStream();
					out = new FileOutputStream(saveFile);
					int temp = 0;
					byte[] buf = new byte[1024];
					while ((temp = input.read(buf, 0, buf.length))!=-1) {
						out.write(buf, 0, temp);
					}
				} catch (IOException e) {
					throw e;
				}finally{
					input.close();
					out.close();
				}
			}
		}
		return names;
	}
}